package highlevel.thread;

public class ThreadCoopration {
	private Account account = new Account();
	private Thread thread1 = new DepositeThread();
	private Thread thread2 = new WithdrawThread();
	
	public ThreadCoopration(){
		thread1.start();
		thread2.start();
	}
	
	public static void main(String[] args) {
		new ThreadCoopration();
		
	}

	//A thread for  adding an amount to the account 
	class DepositeThread extends Thread {
		public void run(){
			while(true){
				account.deposit((int)(Math.random()*10)+1);
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//A thread for subtracting an account from the account
	class WithdrawThread extends Thread{
		public void run(){
			while(true){
				account.withDraw((int)(Math.random()*10)+1);

			}
		}
	}
	
	//an inner class for account
	class Account {
		private int balance = 0;
		
		public int getBalance(){
			return balance;
		}
		
		public synchronized void deposit(int amount){
			balance += amount;
			System.out.println("Depoise "+amount+"\t\t\t"+account.getBalance()); 
			notifyAll();
		}
		public synchronized void withDraw(int amount){
			try {
				while(balance < amount)
					wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			balance -= amount;
			System.out.println("\t\t\tWithDraw "+amount+"\t\t"+account.getBalance());
					
		}
	}
	
}
